package tech.jabari.user.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.jabari.user.entity.User;
import tech.jabari.user.service.UserService;
import tech.jabari.utils.JdbcUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static tech.jabari.constants.UMSConstant.VERIFY_CODE;

/**
 * 用户注册的控制器。
 * @author Jabari Lu
 * @title: UserRegisterController
 * @data 2020/08/29 11:08
 */
@Controller
@Slf4j
public class UserRegisterController  {

    @Autowired
    private UserService userService;

    @PostMapping("/userRegister.action")
    @ResponseBody
    protected Map<String, Object> registerUser(User user,
                                               @RequestParam(name="code",required = true) String code,
                                               @RequestParam(name = "headImgFile",required = false)
                                                       MultipartFile headImg,
                                               HttpServletRequest request, HttpSession session) throws IOException {
        log.trace("---------trace:registerUser()... ");
        log.debug("---------debug:registerUser()... ");
        log.info("---------info:registerUser()... ");
        log.warn("---------warn:registerUser()... ");
        log.error("---------error:registerUser()... ");
        log.info("username = " + user.getUsername());
        if(null == user.getUsername()) {
            throw new RuntimeException("用户名不能为空，请检查！");
        }
        if(user.getUsername().length() > 20) {
            throw new RuntimeException("用户名长度超过20，请检查！");
        }
        log.info("pwd = " + user.getPwd());
        log.info("birth = " + user.getBirthStr());
        Map<String, Object> map = new HashMap<>();
        // 获取session中保存的正确的验证码。
        Object verifyCodeObj = session.getAttribute(VERIFY_CODE);
        if (verifyCodeObj != null) {
            String verifyCode = verifyCodeObj.toString();
            if (!verifyCode.equalsIgnoreCase(code)) {
                map.put(VERIFY_CODE,"-1");
                return map;
            } else {
                map.put(VERIFY_CODE,"1");
            }
        }

        // ""  -> null
        if ("".equals(user.getBirthStr())) {
            user.setBirthStr(null);
        }
        //2.调用service，将用户信息保存到MySQL。
        userService.saveUser(user,headImg,request);

       return map;
    }


}
